package gdut.imis.service.impl;

import gdut.imis.Utils.Constants;
import gdut.imis.Utils.JwtUtil;
import gdut.imis.Utils.RedisCache;
import gdut.imis.Utils.Result;
import gdut.imis.enums.Status;
import gdut.imis.service.LoginService;
import gdut.imis.vo.UserLoginVo;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 用户登录服务
 * @Author JiaFu
 * @Date 2023/4/11 13:42
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;
    private final RedisCache redisCache;

    @Override
    public Map<String, Object> login(String userName, String password, Integer flag) {
        //AuthenticationManager authenticate 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userName, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果验证没有通过给用户提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登陆失败，账号或密码错误");
        }
        //认证通过，使用username生成一个jwt，jwt返回给前端,用户信息也返回给前端
        UserLoginVo userLoginVo = (UserLoginVo) authenticate.getPrincipal();
        HashMap<String, Object> resMap = new HashMap<>();
        HashMap<String, Object> curMap = new HashMap<>();
        String username = null;
        String token = null;
        //如果是管理员
        if (userLoginVo.isManager()) {
            username = userLoginVo.getManager().getPhone();
            token = JwtUtil.createJWT(username);
            curMap.put(Constants.TOKEN, token);
            curMap.put("userInfo", userLoginVo.getManager());
            curMap.put("isManager", true);
        } else {//普通用户
            username = userLoginVo.getUser().getIdCard();
            token = JwtUtil.createJWT(username);
            curMap.put(Constants.TOKEN, token);
            curMap.put("userInfo", userLoginVo.getUser());
            curMap.put("isManager", false);
        }
        //把完整的用户信息存入到redis，key为login:+username
        redisCache.setCacheObject("login:" + username, userLoginVo);
        resMap.put(Constants.DATA_LIST, curMap);
        resMap.put(Constants.STATUS, Status.SUCCESS);
        return resMap;
    }

    @Override
    public Result logOut() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginVo userLoginVo = (UserLoginVo) authentication.getPrincipal();
        if (userLoginVo != null) {
            String username = userLoginVo.getUsername();
            //删除redis中user的信息
            redisCache.deleteObject("login:" + username);
            return Result.success("推出登录成功");
        } else {
            return Result.error(Status.FAILED);
        }
    }
}
